import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { EnglishContent } from '@/types';
import { Platform } from 'react-native';

interface ContentState {
  contents: EnglishContent[];
  favorites: string[]; // IDs of favorite content
  recentlyPlayed: string[]; // IDs of recently played content
  isLoading: boolean;
  error: string | null;
  fetchContents: () => Promise<void>;
  toggleFavorite: (contentId: string) => void;
  addToRecentlyPlayed: (contentId: string) => void;
}

// Mock content data
const mockContents: EnglishContent[] = [
  {
    id: '1',
    title: 'Hello',
    english: 'Hello, how are you?',
    chinese: '你好，你好吗？',
    audioUrl: 'https://example.com/audio/hello.mp3',
    type: 'phrase',
    difficulty: 'beginner',
    tags: ['greeting', 'basic'],
    imageUrl: 'https://images.unsplash.com/photo-1577563908411-5077b6dc7624?ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=80',
  },
  {
    id: '2',
    title: 'Apple',
    english: 'This is an apple.',
    chinese: '这是一个苹果。',
    audioUrl: 'https://example.com/audio/apple.mp3',
    type: 'sentence',
    difficulty: 'beginner',
    tags: ['food', 'fruit'],
    imageUrl: 'https://images.unsplash.com/photo-1570913149827-d2ac84ab3f9a?ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=80',
  },
  {
    id: '3',
    title: 'Cat',
    english: 'The cat is sleeping on the bed.',
    chinese: '猫在床上睡觉。',
    audioUrl: 'https://example.com/audio/cat.mp3',
    type: 'sentence',
    difficulty: 'beginner',
    tags: ['animal', 'pet'],
    imageUrl: 'https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=80',
  },
  {
    id: '4',
    title: 'School',
    english: 'I go to school every day.',
    chinese: '我每天去学校。',
    audioUrl: 'https://example.com/audio/school.mp3',
    type: 'sentence',
    difficulty: 'beginner',
    tags: ['daily', 'education'],
    imageUrl: 'https://images.unsplash.com/photo-1503676260728-1c00da094a0b?ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=80',
  },
  {
    id: '5',
    title: 'Little Red Riding Hood',
    english: 'Once upon a time, there was a little girl who lived in a village near the forest. She was called Little Red Riding Hood.',
    chinese: '从前，有一个小女孩住在森林附近的村庄里。她被称为小红帽。',
    audioUrl: 'https://example.com/audio/red-riding-hood.mp3',
    type: 'story',
    difficulty: 'intermediate',
    tags: ['story', 'fairy tale'],
    imageUrl: 'https://images.unsplash.com/photo-1588182590139-a8c2fc450fd5?ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=80',
  },
  {
    id: '6',
    title: 'Colors',
    english: 'Red, blue, green, yellow, purple, orange, black, white.',
    chinese: '红色，蓝色，绿色，黄色，紫色，橙色，黑色，白色。',
    audioUrl: 'https://example.com/audio/colors.mp3',
    type: 'word',
    difficulty: 'beginner',
    tags: ['colors', 'basic'],
    imageUrl: 'https://images.unsplash.com/photo-1513364776144-60967b0f800f?ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=80',
  },
  {
    id: '7',
    title: 'Weather',
    english: 'Today is sunny. Yesterday was rainy. Tomorrow might be cloudy.',
    chinese: '今天是晴天。昨天是雨天。明天可能多云。',
    audioUrl: 'https://example.com/audio/weather.mp3',
    type: 'sentence',
    difficulty: 'intermediate',
    tags: ['weather', 'daily'],
    imageUrl: 'https://images.unsplash.com/photo-1592210454359-9043f067919b?ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=80',
  },
  {
    id: '8',
    title: 'Family',
    english: 'This is my family. I have a mother, a father, a sister, and a brother.',
    chinese: '这是我的家人。我有一个妈妈，一个爸爸，一个姐姐和一个弟弟。',
    audioUrl: 'https://example.com/audio/family.mp3',
    type: 'sentence',
    difficulty: 'beginner',
    tags: ['family', 'people'],
    imageUrl: 'https://images.unsplash.com/photo-1511895426328-dc8714191300?ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=80',
  },
];

// Create a fallback storage for web environments where AsyncStorage might not be available
const createNoopStorage = () => {
  return {
    getItem: (_name: string) => Promise.resolve(null),
    setItem: (_name: string, _value: string) => Promise.resolve(),
    removeItem: (_name: string) => Promise.resolve(),
  };
};

// Use AsyncStorage when available, otherwise use a noop storage
const storage = Platform.OS === 'web' 
  ? createNoopStorage()
  : AsyncStorage;

export const useContentStore = create<ContentState>()(
  persist(
    (set, get) => ({
      contents: [],
      favorites: [],
      recentlyPlayed: [],
      isLoading: false,
      error: null,
      
      fetchContents: async () => {
        set({ isLoading: true, error: null });
        
        try {
          // Simulate API call
          await new Promise(resolve => setTimeout(resolve, 1000));
          
          set({ 
            contents: mockContents,
            isLoading: false 
          });
        } catch (error) {
          set({ 
            error: error instanceof Error ? error.message : 'Failed to fetch content',
            isLoading: false 
          });
        }
      },
      
      toggleFavorite: (contentId: string) => {
        const { favorites } = get();
        
        if (favorites.includes(contentId)) {
          set({ favorites: favorites.filter(id => id !== contentId) });
        } else {
          set({ favorites: [...favorites, contentId] });
        }
      },
      
      addToRecentlyPlayed: (contentId: string) => {
        const { recentlyPlayed } = get();
        
        // Remove if already exists to avoid duplicates
        const filtered = recentlyPlayed.filter(id => id !== contentId);
        
        // Add to the beginning of the array (most recent first)
        set({ recentlyPlayed: [contentId, ...filtered].slice(0, 10) }); // Keep only 10 most recent
      }
    }),
    {
      name: 'content-storage',
      storage: createJSONStorage(() => storage),
    }
  )
);